//
//  YBTransferViewController.m
//  Nectar
//
//  Created by famer on 2023/11/12.
//  Copyright © 2023 asance. All rights reserved.
//

#import "YBTransferViewController+LayoutConstraints.h"
#import "YBTransferResultViewController.h"
#import "RevDataWithdrawGetBalance.h"
#import "YBTostView.h"

@interface YBTransferViewController ()<UITextFieldDelegate>
YBPropertyCopySetter(NSString, coinUnit);
YBPropertyCopySetter(NSString, balance);

@end

@implementation YBTransferViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kWhiteColor;
    
    [self.view addSubview:self.navigationBar];
    [self.view addSubview:self.contentView];
    [self.contentView addSubview:self.toLabel];
    
    [self.contentView addSubview:self.addressContentView];
    [self.addressContentView addSubview:self.addressTextField];
    [self.addressContentView addSubview:self.addressImageView];

    [self.contentView addSubview:self.amountLabel];
    [self.contentView addSubview:self.balanceLabel];
    [self.contentView addSubview:self.amountContentView];
    [self.amountContentView addSubview:self.amountField];
    [self.amountContentView addSubview:self.amountLineView];
    [self.amountContentView addSubview:self.memoLabel];
    
    [self.contentView addSubview:self.nextStepView];

    [self updateUI];
    [self setLayoutConstraints];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationBar resetBarItemState];
    
    self.addressTextField.text = nil;
    self.amountField.text = nil;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self withdrawGetBalance];
}

#pragma mark - Private Method
- (void)updateUI{
    self.addressContentView.clipsToBounds = YES;
    self.addressContentView.layer.cornerRadius = 10;
    
    self.amountContentView.clipsToBounds = YES;
    self.amountContentView.layer.cornerRadius = 10;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onTextFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
}

- (void)toTransferResultViewController{
    // 获取当前日期并进行格式化
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSString *formattedDate = [dateFormatter stringFromDate:[NSDate date]];

    NSLog(@"Formatted Date: %@", formattedDate);

    YBTransferResultViewController *viewcontroller = [[YBTransferResultViewController alloc] init];
    viewcontroller.date = formattedDate;
    viewcontroller.coinType = self.coinType;
    viewcontroller.amount = self.amountField.text;
    viewcontroller.unit = @"USDT";
    viewcontroller.address = self.addressTextField.text;
    viewcontroller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}

- (void)toTransferAction{
    NSDecimalNumber *balanceBig = [NSDecimalNumber decimalNumberWithString:self.balance];
    NSDecimalNumber *amountBig = [NSDecimalNumber decimalNumberWithString:self.amountField.text];
    if ([balanceBig isEqualToNumber:NSDecimalNumber.notANumber]){
        [YBTostView showWithTitle:@"The balance is 0."];
        return;
    }
    if ([amountBig isEqualToNumber:NSDecimalNumber.notANumber]){
        [YBTostView showWithTitle:@"The transfer amount cannot be 0."];
        return;
    }

    [self showInputPasswordAlter];
}
- (void)toTransferWithPassword:(NSString *)password{
    if(password==nil || password.length==0) return;
    
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    [params setObject:password forKey:@"password"];
    [params setObject:[self.amountField text] forKey:@"amount"];
    [params setObject:self.coinType forKey:@"coinType"];
    NSString *urlString = [NSString stringWithFormat:@"%@",PathWithdrawCreate];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"toTransferWithPassword: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            [self toTransferResultViewController];
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}


- (void)showInputPasswordAlter{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Enter your password" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // 添加一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Please enter";
        textField.secureTextEntry = YES;
    }];
    
    // 添加取消按钮
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
//    [alertController addAction:cancelAction];
    
    // 添加确认按钮
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Transfer" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UITextField *textField = alertController.textFields.firstObject;

        NSString *inputText = textField.text;
        // 在这里处理用户输入的数据
        NSLog(@"User input: %@", inputText);
        if([[NSObject nullSafeForObject:inputText] length]>0){
            [self toTransferWithPassword:inputText];
        }
    }];
    [alertController addAction:confirmAction];
    
    // 显示警告框
    [self presentViewController:alertController animated:YES completion:nil];
    
}


- (void)withdrawGetBalance{
    [SVProgressHUD show];
    self.view.userInteractionEnabled = NO;
    NSMutableDictionary *params = [NSDictionary baseReqParams];
    [params setObject:self.coinType forKey:@"coinType"];
    
    NSString *urlString = [NSString stringWithFormat:@"%@",PathWithdrawGetBalance];
    
    [[YBHttpRequestManager shareInstance] Post:urlString params:params success:^(NSObject *resultObject) {
        NSLog(@"withdrawGetBalance: %@",resultObject);
        
        self.view.userInteractionEnabled = YES;
        [SVProgressHUD dismiss];
        
        //判断网络是否返回错误信息
        YBResponseModel *obj = [YBResponseModel initWithResponseObject:(NSDictionary *)resultObject];
        if([obj success]){
            RevDataWithdrawGetBalance *result = [RevDataWithdrawGetBalance mj_objectWithKeyValues:obj.data];
            self.coinUnit = result.unit;
            self.balance = result.balance;

            NSDecimalNumber *balanceBit = [NSDecimalNumber decimalNumberWithString:result.balance];
            self.balanceLabel.text = [NSString stringWithFormat:@"%@ %@",[balanceBit stringValue], result.unit];
        }
        
    } failure:^(NSError *error) {
        self.view.userInteractionEnabled = YES;
        YBErrorModel *yerror = [YBErrorModel ErrorObjForNSError:error];
    }];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self resignFirstResponder];
    return YES;
}

#pragma mark - Notification
- (void)onTextFieldTextDidChangeNotification:(NSNotification *)notification{
    @synchronized (self) {
        NSString *addressValue = self.addressTextField.text;
        NSString *amoutValue = self.amountField.text;

        if(addressValue!=nil && addressValue.length>0 && amoutValue!=nil && amoutValue.length>0){
            [self.nextStepView setNextStepButtonEnabled];
        }else{
            [self.nextStepView setNextStepButtonUnabled];
        }
    }
}

#pragma mark - Getter Setter
YBViewGetter(contentView, _contentView, kThemeBackground);
YBViewGetter(addressContentView, _addressContentView, kWhiteColor);
YBViewGetter(amountContentView, _amountContentView, kWhiteColor);
YBViewGetter(amountLineView, _amountLineView, kThemeSplitLineColor);

YBImageViewGetter(addressImageView, _addressImageView, [UIImage imageNamed:@"icon_transfer_contact"]);

YBLabelGetter(toLabel, _toLabel, [UIFont systemFontOfSize:12], @"To", kThemeHintColor, NSTextAlignmentLeft);
YBLabelGetter(amountLabel, _amountLabel, [UIFont systemFontOfSize:12], @"Amount", kThemeHintColor, NSTextAlignmentLeft);
YBLabelGetter(balanceLabel, _balanceLabel, [UIFont systemFontOfSize:12], @"*", [UIColor hexColor:@"9AA0A5"], NSTextAlignmentRight);
YBLabelGetter(memoLabel, _memoLabel, [UIFont systemFontOfSize:12], @"Memo(need 1 TRX)", [UIColor hexColor:@"9AA0A5"], NSTextAlignmentLeft);

- (YBNavigationBar *)navigationBar{
    if(!_navigationBar){
        _navigationBar = [[YBNavigationBar alloc] initWithFrame:CGRectZero];
        _navigationBar.backgroundColor = kWhiteColor;
        [_navigationBar setTitle:@"Transfer" titleColor:kThemeBlackColor];
        [_navigationBar setLeftBarImage:@"icon_nav_back" forState:UIControlStateNormal];
        __weak __typeof(&*self)weakSelf = self;
        _navigationBar.onLeftBarButtonBlock = ^(){
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if(!strongSelf) return;
            
            [strongSelf.navigationController popViewControllerAnimated:YES];
        };
    }
    return _navigationBar;
}

- (YBNextStepView *)nextStepView{
    if(!_nextStepView){
        _nextStepView = [[YBNextStepView alloc] initWithFrame:CGRectZero];
        [_nextStepView setButtonTitle:@"Next"];
        [_nextStepView setNextStepButtonUnabled];
        __weak __typeof(&*self)weakSelf = self;
        _nextStepView.onNextStepBlock = ^{
            __strong __typeof(&*weakSelf)strongSelf = weakSelf;
            if(!strongSelf) return;
            
            [strongSelf toTransferAction];
        };
    }
    return _nextStepView;
}

- (UITextField *)addressTextField{
    if(!_addressTextField){
        _addressTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _addressTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _addressTextField.borderStyle = UITextBorderStyleNone;
        _addressTextField.backgroundColor = kWhiteColor;
        _addressTextField.keyboardType = UIKeyboardTypeDefault;
        _addressTextField.returnKeyType = UIReturnKeyDone;
        _addressTextField.font = [UIFont systemFontOfSize:12];
        _addressTextField.placeholder = @"Transfer address";
        _addressTextField.textColor = kThemeBlackColor;
        _addressTextField.delegate = self;
    }
    return _addressTextField;
}

- (UITextField *)amountField{
    if(!_amountField){
        _amountField = [[UITextField alloc] initWithFrame:CGRectZero];
        _amountField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _amountField.borderStyle = UITextBorderStyleNone;
        _amountField.backgroundColor = kWhiteColor;
        _amountField.keyboardType = UIKeyboardTypeDecimalPad;
        _amountField.returnKeyType = UIReturnKeyDone;
        _amountField.font = [UIFont systemFontOfSize:17];
        _amountField.placeholder = @"0";
        _amountField.textColor = kThemeBlackColor;
        _amountField.delegate = self;
    }
    return _amountField;
}


@end
